import { useEffect } from "react";
import { Table, Space, Drawer, Tree } from "antd";
import { store } from "@/redux/index";
import { useState } from "react";
import { getRoleManageDeteils } from "@/api/modules/login";
import { getFlatArr } from "@/utils/util";

const RoleManage = () => {
	useEffect(() => {
		console.log(store.getState().menu.menuList, "---");
	}, []);

	const columns: any[] = [
		{
			title: "序号",
			render: (text: any, record: any, index: number) => <span>{index + 1}</span>
		},
		{
			title: "菜单显示",
			dataIndex: "title",
			key: "title"
		},
		{
			title: "操作",
			dataIndex: "id",
			key: "id",
			render: (text: any) => (
				<Space size="middle">
					<a onClick={() => viewPermission(text)}>查看权限</a>
				</Space>
			)
		}
	];

	const data = [
		{
			id: 0,
			title: "admin"
		},
		{
			id: 1,
			title: "user"
		}
	];

	const [open, setOpen] = useState(false);

	const showDrawer = () => {
		setOpen(true);
	};

	const onClose = () => {
		setOpen(false);
	};

	const viewPermission = async (id: number) => {
		showDrawer();

		const { data } = await getRoleManageDeteils(id);
		if (data) {
			setCheckedKeys(getFlatArr(data).map(item => item.path));
		}
	};

	const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true); // 是否自动展开父节点
	const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]); // 展开指定的树节点
	const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]); // 选中复选框的树节点
	const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]); // 设置选中的树节点

	const onSelect = (selectedKeysValue: React.Key[], info: any) => {
		console.log("onSelect", { info, selectedKeysValue, setSelectedKeys });
		// setSelectedKeys(selectedKeysValue); // 设置选中的树节点
	};
	const onExpand = (expandedKeysValue: React.Key[]) => {
		console.log("onExpand", expandedKeysValue);
		setExpandedKeys(expandedKeysValue);
		setAutoExpandParent(false);
	};
	const onCheck = (checked: React.Key[] | { checked: React.Key[]; halfChecked: React.Key[] }) => {
		const checkedKeysValue = Array.isArray(checked) ? checked : checked.checked;
		console.log("onCheck", checkedKeysValue);
		setCheckedKeys(checkedKeysValue);
	};

	return (
		<div className="card content-box">
			<Table dataSource={data} columns={columns} rowKey="title" />
			<Drawer title="查看权限" placement="right" closable={false} onClose={onClose} visible={open}>
				<Tree
					checkable
					onExpand={onExpand}
					expandedKeys={expandedKeys}
					autoExpandParent={autoExpandParent}
					onCheck={onCheck}
					checkedKeys={checkedKeys}
					onSelect={onSelect}
					selectedKeys={selectedKeys}
					treeData={store.getState().menu.menuList}
					fieldNames={{ key: "path" }}
				/>
			</Drawer>
		</div>
	);
};

export default RoleManage;
